package com.metel.mservice.common.context;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * OpenAPIContextManager
 * 
 * @author sr80.choi
 */
public class OpenAPIContextManager {
	private static final Logger logger = LoggerFactory.getLogger(OpenAPIContextManager.class);

	// Context Property Key
	private static final String Context_Key = "env";

	// Context for production server
	private static final String Production_Context = "Prod";

	private static OpenAPIContext currentContext;

	private OpenAPIContextManager() {
		// do nothing..
	}

	public static OpenAPIContext getContext() {
		if (currentContext == null) {
			currentContext = createContext();
		}

		return currentContext;
	}

	private static OpenAPIContext createContext() {
		OpenAPIContext context = null;

		String property = System.getProperty(Context_Key, Production_Context);
		String className = property.substring(0, 1).toUpperCase() + property.substring(1) + "Context";
		className = "com.samsungchaton.common.context." + validate(className);
		try {
			ClassLoader classLoader = OpenAPIContextManager.class.getClassLoader();
			Class<?> clazz = classLoader.loadClass(className);
			Object instance = clazz.newInstance();

			if (instance instanceof OpenAPIContext) {
				context = (OpenAPIContext) instance;
			}
		} catch (Exception e) {
			if (logger.isErrorEnabled()) 
				logger.error("OpenAPIContextManager Exception(error msg={})", e.getMessage());
		} finally {
			if (context == null) {
				context = new DefaultContext(property);
				if (logger.isErrorEnabled()) 
					logger.error("[OpenAPIContextManager] Just loaded DefaultContext for {} env.", property);
			}
		}

		return context;
	}

	public static boolean isLocalEnvironment() {
		String property = System.getProperty(Context_Key, Production_Context);
		return property.toLowerCase().equals("local");
	}
	
	private static String validate(String className){
		if( StringUtils.isBlank(className) ){
			className = Production_Context + "Context";
		}
		return className;
	}
}
